package com.wgh.cart.service.impl;

import com.wgh.cart.entity.CartItem;
import com.wgh.cart.service.CartService;
import com.wgh.common.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 购物车服务实现类
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    // 购物车Redis Key前缀
    private static final String CART_KEY_PREFIX = "cart:user:";
    // 购物车过期时间（7天）
    private static final long CART_EXPIRE_DAYS = 7;

    @Override
    public Result<Boolean> addToCart(Long userId, Long productId, Long skuId, Integer quantity, String attributes) {
        try {
            // 获取用户购物车Key
            String cartKey = CART_KEY_PREFIX + userId;

            // 创建购物车项
            CartItem cartItem = new CartItem();
            cartItem.setId(System.currentTimeMillis()); // 使用时间戳作为临时ID
            cartItem.setUserId(userId);
            cartItem.setProductId(productId);
            cartItem.setSkuId(skuId);
            cartItem.setQuantity(quantity);
            cartItem.setAttributes(attributes);
            cartItem.setSelected(true);
            cartItem.setCreateTime(LocalDateTime.now());
            cartItem.setUpdateTime(LocalDateTime.now());

            // 将购物车项序列化为JSON字符串
            String cartItemJson = objectMapper.writeValueAsString(cartItem);

            // 存储到Redis，使用cartItemId作为字段名
            redisTemplate.opsForHash().put(cartKey, cartItem.getId().toString(), cartItemJson);

            // 设置过期时间
            redisTemplate.expire(cartKey, CART_EXPIRE_DAYS, TimeUnit.DAYS);

            return Result.success(true);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("添加购物车失败");
        }
    }

    @Override
    public Result<Boolean> updateCartItemQuantity(Long userId, Long cartItemId, Integer quantity) {
        try {
            String cartKey = CART_KEY_PREFIX + userId;
            Object cartItemJsonObj = redisTemplate.opsForHash().get(cartKey, cartItemId.toString());

            if (cartItemJsonObj != null) {
                // 反序列化购物车项
                CartItem cartItem = objectMapper.readValue(cartItemJsonObj.toString(), CartItem.class);
                cartItem.setQuantity(quantity);
                cartItem.setUpdateTime(LocalDateTime.now());

                // 重新序列化并存储
                String updatedCartItemJson = objectMapper.writeValueAsString(cartItem);
                redisTemplate.opsForHash().put(cartKey, cartItemId.toString(), updatedCartItemJson);

                return Result.success(true);
            } else {
                return Result.error("购物车项不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新购物车数量失败");
        }
    }

    @Override
    public Result<Boolean> updateCartItemSelected(Long userId, Long cartItemId, Boolean selected) {
        try {
            String cartKey = CART_KEY_PREFIX + userId;
            Object cartItemJsonObj = redisTemplate.opsForHash().get(cartKey, cartItemId.toString());

            if (cartItemJsonObj != null) {
                // 反序列化购物车项
                CartItem cartItem = objectMapper.readValue(cartItemJsonObj.toString(), CartItem.class);
                cartItem.setSelected(selected);
                cartItem.setUpdateTime(LocalDateTime.now());

                // 重新序列化并存储
                String updatedCartItemJson = objectMapper.writeValueAsString(cartItem);
                redisTemplate.opsForHash().put(cartKey, cartItemId.toString(), updatedCartItemJson);

                return Result.success(true);
            } else {
                return Result.error("购物车项不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("更新购物车选中状态失败");
        }
    }

    @Override
    public Result<Boolean> updateCartItemsSelected(Long userId, Boolean selected) {
        try {
            String cartKey = CART_KEY_PREFIX + userId;
            Map<Object, Object> cartItemsMap = redisTemplate.opsForHash().entries(cartKey);

            if (!cartItemsMap.isEmpty()) {
                for (Map.Entry<Object, Object> entry : cartItemsMap.entrySet()) {
                    try {
                        CartItem cartItem = objectMapper.readValue(entry.getValue().toString(), CartItem.class);
                        cartItem.setSelected(selected);
                        cartItem.setUpdateTime(LocalDateTime.now());
                        String updatedCartItemJson = objectMapper.writeValueAsString(cartItem);
                        redisTemplate.opsForHash().put(cartKey, entry.getKey(), updatedCartItemJson);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                return Result.success(true);
            }
            return Result.success(true);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("批量更新购物车选中状态失败");
        }
    }

    @Override
    public Result<Boolean> removeFromCart(Long userId, Long cartItemId) {
        try {
            String cartKey = CART_KEY_PREFIX + userId;
            redisTemplate.opsForHash().delete(cartKey, cartItemId.toString());
            return Result.success(true);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除购物车项失败");
        }
    }

    @Override
    public Result<Boolean> clearCart(Long userId) {
        try {
            String cartKey = CART_KEY_PREFIX + userId;
            redisTemplate.delete(cartKey);
            return Result.success(true);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("清空购物车失败");
        }
    }

    @Override
    public Result<List<CartItem>> getCartList(Long userId) {
        try {
            String cartKey = CART_KEY_PREFIX + userId;
            Map<Object, Object> cartItemsMap = redisTemplate.opsForHash().entries(cartKey);

            List<CartItem> cartItems = new ArrayList<>();
            if (!cartItemsMap.isEmpty()) {
                for (Object value : cartItemsMap.values()) {
                    try {
                        CartItem cartItem = objectMapper.readValue(value.toString(), CartItem.class);
                        cartItems.add(cartItem);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                // 按更新时间排序
                cartItems.sort((a, b) -> b.getUpdateTime().compareTo(a.getUpdateTime()));
            }
            return Result.success(cartItems);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取购物车列表失败");
        }
    }

    @Override
    public Result<List<CartItem>> getSelectedCartItems(Long userId) {
        try {
            String cartKey = CART_KEY_PREFIX + userId;
            Map<Object, Object> cartItemsMap = redisTemplate.opsForHash().entries(cartKey);

            List<CartItem> selectedItems = new ArrayList<>();
            if (!cartItemsMap.isEmpty()) {
                for (Object value : cartItemsMap.values()) {
                    try {
                        CartItem cartItem = objectMapper.readValue(value.toString(), CartItem.class);
                        if (Boolean.TRUE.equals(cartItem.getSelected())) {
                            selectedItems.add(cartItem);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return Result.success(selectedItems);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取选中的购物车项失败");
        }
    }

    @Override
    public Result<Integer> getCartItemCount(Long userId) {
        try {
            String cartKey = CART_KEY_PREFIX + userId;
            Map<Object, Object> cartItemsMap = redisTemplate.opsForHash().entries(cartKey);

            if (!cartItemsMap.isEmpty()) {
                return Result.success(cartItemsMap.size());
            }
            return Result.success(0);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取购物车数量失败");
        }
    }
}